class UserInfo {
    constructor(
        userName = '',
        roleName = '',
        lastLoginTime = '',
        lastLoginIp = '') {
        this.userName = userName;
        this.roleName = roleName;
        this.lastLoginTime = lastLoginTime;
        this.lastLoginIp = lastLoginIp;
    }
}

const homeGridCard = {
    name: "home-grid-card",
    template: `
        <a href="#" v-if="url" @click="view()">
            <div class="home-grid__li">
          <div class="home-grid__card">
            <span class="home-grid__count" v-if="countFunction">{{count}}</span>
            <img v-if="img" :src="img" alt=""/>
          </div>
          <div class="home-grid__name">{{title}}</div>
        </div>
        </a>
        
        <div v-else class="home-grid__li">
          <div class="home-grid__card">
            <span class="home-grid__count" v-if="countFunction">{{count}}</span>
            <img v-if="img" :src="img" alt=""/>
          </div>
          <div class="home-grid__name">{{title}}</div>
        </div>
    `,
    props: {
        url: {
            type: [String],
            required: false,
            default: undefined,
        },
        params: {
            type: [Object],
            required: false,
            default: undefined,
        },
        img: {
            type: [String],
            required: false,
            default: "",
        },
        title: {
            type: [String],
            required: true
        },
        countFunction: {
            type: [Function],
            required: false,
            default: null,
        }
    },
    data() {
        return {
            count: 0,
        }
    },
    methods: {
        view() {
            forward(this.url, this.params);
        }
    },
    async mounted() {
        if (this.countFunction) {
            this.count = await (this.countFunction());
        }
    }

}

const indexPage = new Vue({
    el: '#index',
    components: {
        'home-grid-card': homeGridCard,
    },
    data: {
        netCardTimer: '',
        tableData: [],
        userInfo: new UserInfo(),
        systemInfo: {
            currentTime: '2019-05-09 13:44:52.261',
            ranTime: '0天2小时2分',
            diskInfo: {
                total: 188.00302,
                free: 80.46094,
            },
            cpuInfo: {
                hz: 2400,
                amount: 4,
            },
            memoryInfo: {
                mTotal: 0,
                mFree: 0,
                mUsed: 0,
                mUsedPercent: 0,
                cacheTotal: 0,
                cacheUsedPercent: 0,
                buffersTotal: 0,
                mRealUsed: 0,
                mRealFreePercent: 0,
                mRealUsedPercent: 0,
                swapTotal: 0,
                swapUsed: 0,
                swapFree: 0,
                swapUsedPercent: 0,
            },
            netWorkInfoList: [
                {
                    networkCardName: 'eth0',
                    receivedFlow: '0.00KB',
                    sentFlow: '0.00KB',
                },
            ],
            systemAverageLoad: '',
            startTime: 0,
        },
        totalList: {
            baseOperCompany: 0,
            baseHouseOfficer: 0,
            baseHouseInfo: 0,
            baseIpAddressInfo: 0,
            baseCustomer: 0,
            baseMonitorDevice: 0,
            insAdminControl: 0,
            insAccessLogQuery: 0,
            insFile: 0,
            insMonitor: 0,
            insFilter: 0,
            slogMonitorLog: 0,
            slogAbnormalIp: 0,
            moIllegalInfo: 0,
            rIllegalMedia: 0,
            slogHotDomain: 0,
            slogHotIp: 0,
            insWorkOrder: 0,
            moFilingSupervise: 0,
            slogIllegalSite: 0,
        },
        otherList: {
            baseOperCompanyNotReport: 0,
            baseHouseInfoNotReport: 0,
            baseHouseOfficerNotReport: 0,
            baseIpAddressInfoNotReport: 0,
            insAccessLogQueryNotReport: 0,
            insMonitorNotReport: 0,
            insFilterNotReport: 0,
            slogAbnormalIpNotReport: 0,
            moFilingSuperviseNotReport: 0,
            slogIllegalSiteNotReport: 0,
            moIllegalInfoNotReport: 0,
            rIllegalMediaNotReport: 0,
        },
        currentUser: {},
        tlogAlarm: {
            alarmType: 4,
            viewStatus: 1,
        },
        tempRanTime: 0,
        sourceGridCardList: [
            {
                img: "/static/img/icon/1.png",
                title: "非法IP",
                url: "monitor-log/admin_monitor_ip",
                params: {},
                countFunction: async () => await slogAbnormalIpApi.notReportTotal(),
            },
            {
                img: "/static/img/icon/2.png",
                title: "违法网站",
                url: "monitor-log/admin_monitor_web",
                params: {},
                countFunction: async () => await slogIllegalSiteApi.notReportTotal(),
            },
            {
                img: "/static/img/icon/3.png",
                title: "非法信息",
                url: "illegal-monitor/admin_illegal",
                params: {},
                countFunction: async () => await moIllegalInfoApi.notDealTotal(),
            },
            {
                img: "/static/img/icon/4.png",
                title: "非法多媒体",
                url: "illegal-monitor/admin_multimedia",
                params: {},
                countFunction: async () => await rIllegalMediaDayApi.notReportTotal(),
            },
            {
                img: "/static/img/icon/5.png",
                title: "活跃域名",
                url: "monitor-log/admin_active_domain",
                params: {},
                countFunction: async () => await slogHotDomainApi.notReportTotal(),
            },
            {
                img: "/static/img/icon/6.png",
                title: "活跃IP",
                url: "monitor-log/admin_active_ip",
                params: {},
                countFunction: async () => await slogHotIpApi.notReportTotal(),
            },
            {
                img: "/static/img/icon/7.png",
                title: "告警日志",
                url: "security-log/admin_alarm_log",
                params: {},
                countFunction: async () => await tlogAlarmApi.notViewTotal(),
            },
            {
                img: "/static/img/icon/8.png",
                title: "用户管理",
                url: "system-config/admin_privilege_admin_list",
                params: {},
            },
            {
                img: "/static/img/icon/9.png",
                title: "系统设置",
                url: "system-config/admin_sysconfig",
                params: {},
            },
        ],
        homeGridCardList: [],
        selectedModuleIds: [],
        moduleListDialogVisible: false,
        illegalMultimediaTableData: [],
        illegalInfoTableData: [],
        networkCardTypeMap: {
            '1': '镜像口',
            '2': '出包口',
        },
        serverInfo: {
            serverStatus: [],
            mirrorNetworkCardStatus: [],
        },
        serverStatusTime:''
    },
    computed: {
        sourceGridCardMap() {
            const map = {};
            const sourceGridCardList = this.sourceGridCardList;
            if (!sourceGridCardList || (Array.isArray(sourceGridCardList) && sourceGridCardList.length === 0)) {
                return map;
            }
            this.sourceGridCardList.forEach(data => {
                map[data['_id']] = data;
            })
            return map;
        }
    },
    methods: {
        //获取网卡数据
        async getNetCardData() {
            let netCardDataList = await indexApi.getNetCardData()
            for (let i = 0; i < netCardDataList.length; i++) {
                let tmp = {
                    health: netCardDataList[i].inputMissedPercents < 1 ,
                    port: netCardDataList[i].portId,
                    type: netCardDataList[i].portType,
                    flow: netCardDataList[i].portType === 1 ? netCardDataList[i].inputBytes :
                        netCardDataList[i].outputBytes,
                    dataNum: netCardDataList[i].portType === 1 ? netCardDataList[i].inputPackets :
                        netCardDataList[i].outputPackets,
                    speedRate: netCardDataList[i].portType === 1 ? netCardDataList[i].inputErrorPercents :
                        netCardDataList[i].outputErrorPercents,
                    packetLossRate: netCardDataList[i].inputMissedPercents,

                }
                this.$set(this.serverInfo.mirrorNetworkCardStatus, i, tmp)
            }
            console.log(this.serverInfo.mirrorNetworkCardStatus)

        },
        getNetworkCardType(key) {
            return this.networkCardTypeMap[key];
        },
        async initUserInfo() {
            const res = await indexApi.initUserInfo();
            const {lastLoginTime = ''} = res;
            res.lastLoginTime = TableColumn.datetimeFormat('', '', lastLoginTime);
            this.userInfo = res;
        },
        async initSystemInfo() {
            this.systemInfo = await sysInfoApi.info();
        },
        async getCurrentUser() {
            this.currentUser = await sysLoginApi.currentUser();
        },
        async initTotal() {
            const res = await indexApi.total();
            if (!res) {
                return;
            }
            const totalIndicator = res['totalIndicator'];
            if (totalIndicator) {
                totalIndicator.forEach(obj => {
                    this.totalList[obj.key] = obj.val;
                })
            }

            const otherIndicators = res['otherIndicators'];
            if (otherIndicators) {
                otherIndicators.forEach(obj => {
                    this.otherList[obj.key] = obj.val;
                })
            }
        },
        openModuleListDialog() {
            this.selectedModuleIds = this.getCacheSelectedModuleIds();
            this.moduleListDialogVisible = true;
        },
        saveModuleList() {
            localStorage.setItem(`selectedModuleIds:${this.userInfo.id}`, JSON.stringify(this.selectedModuleIds));
            this.homeGridCardList = this.getModuleByIds(this.selectedModuleIds);
            this.moduleListDialogVisible = false;
        },
        getModuleByIds(idArr) {
            if (!idArr || (Array.isArray(idArr) && idArr.length === 0)) {
                return [];
            }
            return idArr.map(hashcode => {
                return this.sourceGridCardMap[hashcode]
            });
        },
        initHomeGridCardList() {
            this.homeGridCardList = this.getSelectedModuleList();
        },
        getCacheSelectedModuleIds() {
            return JSON.parse(localStorage.getItem(`selectedModuleIds:${this.userInfo.id}`) || "[]")
        },
        getSelectedModuleList() {
            return this.getModuleByIds(this.getCacheSelectedModuleIds());
        },
        initSourceGridCardList() {
            const sourceGridCardList = this.sourceGridCardList;
            if (!sourceGridCardList || (Array.isArray(sourceGridCardList) && sourceGridCardList.length === 0)) {
                return;
            }
            //添加hashcode为id
            this.sourceGridCardList = this.sourceGridCardList.map(data => {
                const obj = {};
                obj['title'] = data['title'];
                obj['img'] = data['img'];
                data['_id'] = global.hashcode(obj);
                return data;
            });
        },
        async initMoIllegalInfoTable() {
            this.illegalInfoTableData = await moIllegalInfoApi.warnList();
        },
        async initMoIllegalMediaTable() {
            this.illegalMultimediaTableData = await moIllegalMediaApi.warnList();
        },
        async initServerInfo() {
            const res  = await indexApi.initServerInfo();

            if(!Array.isArray(res)) return

            const serveStatus = res.map(el =>{
                const { host,cpuInfo:{ cpuRate },appStatus, memoryInfo:{ usedRate },serverCnName,diskInfoList } = el

                const max = diskInfoList.sort((a,b) => b.usedPercent - a.usedPercent)[0]

                return {
                    ip:host,
                    name:serverCnName,
                    cpuOc: Math.floor(cpuRate * 100),
                    memHealth: Math.floor(usedRate * 100) <= 80,
                    memOc: Math.floor(usedRate * 100),
                    cpuHealth: Math.floor(cpuRate * 100) <= 80,
                    health: max == undefined ? 0 : Math.floor(max.usedPercent),
                }
            })

            this.serverInfo.serverStatus = serveStatus

            // this.serverInfo = {
            //     serverStatus: [
            //         {
            //             health: 50,
            //             ip: '192.168.1.1',
            //             name: "拦截器",
            //             cpuOc: 80,
            //             cpuHealth: false,
            //             memOc: 80,
            //             memHealth: false,
            //         }
            //     ],
            //     mirrorNetworkCardStatus: [
            //         {
            //             health: true,
            //             flow: 45254,
            //             type: 1,
            //             port: 8080,
            //             dataNum: '458,459,403',
            //             speedRate: '89,523,340',
            //             packetLossRate: '0.1091',
            //         }
            //     ],
            // }
        }
    },
    async created() {
        this.initSourceGridCardList();
        this.initHomeGridCardList();
        await this.initMoIllegalInfoTable();
        await this.initMoIllegalMediaTable();
        await this.initTotal();
        await this.initUserInfo();
        await this.initServerInfo();
        await this.getNetCardData();
    },
    async mounted() {
        //创建网卡数据定时器
        this.netCardTimer = setInterval(this.getNetCardData, 5000);
        this.serverStatusTime = setInterval(this.initServerInfo,5000);
    },
    beforeDestroy() {
        clearInterval(this.netCardTimer);
        clearInterval(this.serverStatusTime);
    }
})
